import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, FindOptionsWhere, Repository } from 'typeorm';
import { Student } from './models/student.entity';
import { encryptPassword } from '../../util';
import { ENCRYPT_SALT } from '../../constant';
import { Result } from '../../dto/result.type';
import { StudentType } from './dto/student.type';

@Injectable()
export class StudentService {
  constructor(
    @InjectRepository(Student) private StudentRepository: Repository<Student>,
  ) {}

  // 新增一个学员
  async createStudent(entity: DeepPartial<Student>): Promise<Result> {
    // 判断是否已经存在该用学员
    if (entity.account) {
      const Student = await this.StudentRepository.findOne({
        where: {
          account: entity.account,
        },
      });
      if (Student) return { code: false, message: '用户名已存在' };
    }

    // 加密
    entity.password = encryptPassword(entity.password, ENCRYPT_SALT);

    const res = await this.StudentRepository.insert(entity);
    return {
      code: !!res,
    };
  }

  // 删除一个学员
  async delStudent(id: string): Promise<boolean> {
    const res = await this.StudentRepository.delete(id);
    return res.affected > 0;
  }

  // 更新一个用户其他信息
  async updateStudent(
    id: string,
    entity: DeepPartial<Student>,
  ): Promise<Result> {
    console.log(entity);
    const res = await this.StudentRepository.update(id, entity);
    const result = res.affected > 0;
    return result
      ? {
          message: '更新成功',
          code: true,
        }
      : {
          message: '更新失败',
          code: false,
        };
  }

  // 查询一个用户通过id
  async findStudentById(id: string): Promise<StudentType> {
    return await this.StudentRepository.findOne({
      where: {
        id,
      },
    });
  }

  // 查询一个用户通过手机号
  async findStudentByTel(tel: string): Promise<StudentType> {
    return await this.StudentRepository.findOne({
      where: {
        tel,
      },
    });
  }

  async findStudents({
    start,
    length,
    where,
  }: {
    start: number;
    length: number;
    where: FindOptionsWhere<Student>;
  }): Promise<[StudentType[], number]> {
    return this.StudentRepository.findAndCount({
      take: length,
      skip: start,
      where,
      order: {
        id: 'DESC',
      },
    });
  }
}
